package gameoflife.clips;

import gameoflife.main.Game;

import java.util.Iterator;

import CLIPSJNI.Environment;
import CLIPSJNI.FactAddressValue;
import CLIPSJNI.IntegerValue;
import CLIPSJNI.MultifieldValue;
import CLIPSJNI.SymbolValue;


public class ClipsProcesses {
	
	public static void initAsserts(Environment clipsenv, boolean[][] grid) {
		for (int row = 0; row < grid.length; row++) {
			for (int col = 0; col < grid[0].length; col++) {
				StringBuilder sb = new StringBuilder();
				sb.append("(automata (mean init) ");
				sb.append("(state ");
				if (grid[row][col]) {
					sb.append("alive");
				} else {
					sb.append("dead");
				}
				sb.append(") ");
				sb.append("(xcoor " + row + ") ");
				sb.append("(ycoor " + col + ") ");
				sb.append(")");
				clipsenv.assertString(sb.toString());
			}
		}
	}
	
	public static boolean[][] getResult(Environment clipsenv) {
		boolean[][] res = new boolean[Game.SIZE][Game.SIZE];

		String evalStr = "(find-all-facts ((?f automata))"
				+ "(eq ?f:mean new))";
		MultifieldValue pv = (MultifieldValue) clipsenv.eval(evalStr);
		for (Iterator itr = pv.listValue().iterator(); itr.hasNext();) {
			FactAddressValue fv = (FactAddressValue) itr.next();
			String st = ((SymbolValue) fv.getFactSlot("state")).stringValue();
			int r = ((IntegerValue) fv.getFactSlot("xcoor")).intValue();
			int c = ((IntegerValue) fv.getFactSlot("ycoor")).intValue();
			if (st.equals("alive")) {
				res[r][c] = true;
			} else {
				res[r][c] = false;
			}
		}
		return res;
	}
}
